package com.zwcl.payment.gateway.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.zwcl.common.core.exception.BusinessException;
import com.zwcl.payment.gateway.constants.PayConstants;
import com.zwcl.payment.gateway.entity.PaymentAccount;
import com.zwcl.payment.gateway.enums.OrderTypeEnum;
import com.zwcl.payment.gateway.enums.PayWayEnum;
import com.zwcl.payment.gateway.mapper.PaymentAccountMapper;
import com.zwcl.payment.gateway.service.PaymentAccountService;
import com.zwcl.common.mybatis.service.impl.BaseServiceImpl;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

/**
 * <p>
 * 微信商户账号 服务实现类
 * </p>
 *
 * @author xieyongping
 * @since 2021-03-15
 */
@Service
public class PaymentAccountServiceImpl extends BaseServiceImpl<PaymentAccountMapper, PaymentAccount> implements PaymentAccountService {

    @Autowired
    private PaymentAccountMapper paymentAccountMapper;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    public static final Integer expire = 30;//缓存失效时间，单位：分钟

    @Override
    public Integer getMchType(Integer orderType, Integer payWay) {
        //默认为1
        Integer mchType = 1;
        if(OrderTypeEnum.GLASS.getValue().equals(orderType)) {
            if (PayWayEnum.WECHAT_MINA_NORMAL.getValue().equals(payWay)) {
                mchType = 1;
            } else if (PayWayEnum.WECHAT_MINA.getValue().equals(payWay)) {
                mchType = 1;
            }
        }
        return mchType;
    }

    /**
     * 根据类型获取微信商户账号
     * @param mchType 商户账号类型
     * @return
     */
    public PaymentAccount getByType(Integer mchType){
        //从缓存获取
        String key = PayConstants.CACHE_KEY_PAYMENT_WEIXIN_ACCOUNT + ":MchType:" + mchType;
        String str = stringRedisTemplate.opsForValue().get(key);
        PaymentAccount paymentAccount;
        if(str == null){
            paymentAccount = this.getOne(new QueryWrapper<PaymentAccount>().lambda().eq(PaymentAccount::getMchType, mchType));
            if(paymentAccount == null){
                //预警通知
                throw new BusinessException("缺少支付配置: mchType=" + mchType);
            }
            stringRedisTemplate.opsForValue().set(key, JSON.toJSONString(paymentAccount), expire, TimeUnit.MINUTES);
        } else {
            paymentAccount = JSON.parseObject(str, PaymentAccount.class);
        }
        return paymentAccount;
    }

    /**
     * 根据mchId获取密钥
     * @param mchId 商户号
     * @return
     */
    public String getSecretKey(String mchId){
        //从缓存获取
        String key = PayConstants.CACHE_KEY_PAYMENT_WEIXIN_ACCOUNT + ":MchId:" + mchId;
        String secretKey = stringRedisTemplate.opsForValue().get(key);
        if(secretKey == null){
            QueryWrapper<PaymentAccount> qw = new QueryWrapper();
            qw.select("secret_key");
            qw.eq("mch_id", mchId);
            qw.last("LIMIT 1");
            PaymentAccount paymentAccount = paymentAccountMapper.selectOne(qw);
            if(paymentAccount == null){
                //预警通知
                throw new BusinessException("缺少支付配置: mchId=" + mchId);
            }
            secretKey = paymentAccount.getSecretKey();
            if(!StringUtils.isBlank(secretKey)) {
                stringRedisTemplate.opsForValue().set(key, secretKey, expire, TimeUnit.MINUTES);
            }
        }
        return secretKey;
    }

    /**
     * 根据subMchId获取密钥
     * @param subMchId 商户号
     * @return
     */
    @Override
    public String getSubSecretKey(String subMchId){
        //从缓存获取
        String key = PayConstants.CACHE_KEY_PAYMENT_WEIXIN_ACCOUNT + ":SubMchId:" + subMchId;
        String subSecretKey = stringRedisTemplate.opsForValue().get(key);
        if(subSecretKey == null){
            QueryWrapper<PaymentAccount> qw = new QueryWrapper();
            qw.select("sub_secret_key");
            qw.eq("sub_mch_id", subMchId);
            qw.last("LIMIT 1");
            PaymentAccount paymentAccount = paymentAccountMapper.selectOne(qw);
            if(paymentAccount == null){
                //预警通知
                throw new BusinessException("缺少支付配置: subMchId=" + subMchId);
            }
            subSecretKey = paymentAccount.getSubSecretKey();
            if(!StringUtils.isBlank(subSecretKey)){
                stringRedisTemplate.opsForValue().set(key, subSecretKey, expire, TimeUnit.MINUTES);
            }
        }
        return subSecretKey;
    }

}
